package com.zk.wx.util;

import com.zk.wx.model.commons.Token;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: ZHANG_KUAN
 * @Description:
 * @Date: Create in 14:15 2017/12/11
 */
public class TokenUtil {
    private static Logger log = LoggerFactory.getLogger(TokenUtil.class);
    /**
     * 获取接口访问凭证
     *
     * @param appid 凭证
     * @param appsecret 密钥
     * @return
     */
    public static Token getToken(String appid, String appsecret, String tokenUrl) {
        Token token = null;
        String requestUrl = tokenUrl.replace("APPID", appid).replace("APPSECRET", appsecret);
        // 发起GET请求获取凭证
        JSONObject jsonObject = HttpUtil.httpRequest(requestUrl,"GET",null);

        if (null != jsonObject) {
            try {
                token = new Token();
                token.setAccessToken(jsonObject.getString("access_token"));
                token.setExpiresIn(jsonObject.getInt("expires_in"));
            } catch (JSONException e) {
                token = null;
                // 获取token失败
                log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        return token;
    }
}
